﻿#region 文件信息

/*----------------------------------------------------------------
//
// 文件名称：
// 文件功能描述：
// 设计要求：
//
// 文 件 名：    ClientMenuManagerViewModel
// 创建者：      杨程
// 创建日期：	    2022/12/15 22:21:43

//----------------------------------------------------------------*/

#endregion



namespace Vampirewal.Admin.Server.ViewModels.ViewModel.SystemManager;

/// <summary>
///
/// </summary>
[VampirewalIoCRegister(ServerViewModelKeys.ClientMenuManagerViewModel)]
public partial class ClientMenuManagerViewModel : BillListBaseVM<Sys_Menu, Sys_Menu>
{
    private IVampirewalCoreEventBusFactory EventBusFactory { get; set; }

    /// <summary>
    ///
    /// </summary>
    public ClientMenuManagerViewModel(IVampirewalCoreDialogMessage dialog, IVampirewalCoreEventBusFactory eventBusFactory,SqlSugarRepository<Sys_Menu> _repMenu, SqlSugarRepository<Sys_Menu> _repSreach) : base(dialog, _repMenu, _repSreach)
    {
        this.EventBusFactory = eventBusFactory;
        //构造函数

        MenuList.LoadFullNodes(RepBill.ToList());

        TreeListViewActionsCommand = new IVampirewalCoreEventCommand[]
        {
            new VampirewalCoreEventCommand("SelectedItemChanged","SelectedItem", new RelayCommand<GeneralTreeContainer<Sys_Menu>>((Selected) =>
            {
                var menu = Selected.TreeNode;
            }))
        };
    }

    //private void TreeListViewSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    //{
    //    var Trees = sender as TreeListView;

    //    if (Trees.SelectedItem is GeneralTreeContainer<Sys_Menu> Selected)
    //    {
    //        var menu = Selected.TreeNode;
    //    }
    //}

    #region [     重写     ]

    protected override void InitVM()
    {
        MenuList = new TreeBuilderByFullLoad<Sys_Menu>();
    }

    protected override IUcViewBase SetView()
    {
        switch (ViewKey)
        {
            case ServerViewKeys.EditClientMenuView:
                return WindowsManager.GetInstance().GetView(ViewKey);

            default:
                throw new NotImplementedException();
        }
    }

    public override void ExecuteBeforeCloseDialogWindow(object obj)
    {
        MenuList.LoadFullNodes(RepBill.ToList());
    }

    #endregion

    #region [     属性     ]

    /// <summary>
    /// 底部页面
    /// </summary>
    [ObservableProperty]
    public IUcViewBase bottomContext;

    public TreeBuilderByFullLoad<Sys_Menu> MenuList { get; set; }

    public IVampirewalCoreEventCommand[] TreeListViewActionsCommand { get; set; }

    private string ViewKey;

    #endregion

    #region [     Command命令     ]

    #region [     分页命令     ]

    /// <summary>
    ///     页码改变命令
    /// </summary>
    public RelayCommand<FunctionEventArgs<int>> PageUpdatedCmd =>
        new Lazy<RelayCommand<FunctionEventArgs<int>>>(() =>
            new RelayCommand<FunctionEventArgs<int>>(PageUpdated)).Value;

    /// <summary>
    ///     页码改变
    /// </summary>
    private void PageUpdated(FunctionEventArgs<int> info)
    {
        EntityList.Clear();

        Page = info.Info;

        GetPageList(w => !string.IsNullOrEmpty(w.BillId), o => new { o.CreateTime }, OrderByType.Asc, true);
    }

    #endregion

    /// <summary>
    /// 添加新菜单命令
    /// </summary>
    [RelayCommand]
    public void AddNewModule()
    {
        ViewKey = ServerViewKeys.EditClientMenuView;

        List<SimplePassData> data = new List<SimplePassData>();

        Sys_Menu menu = new Sys_Menu()
        {
            MenuType = 0,
            ListId = Guid.NewGuid().ToString(),
            ParentId = Guid.Empty.ToString()
        };

        data.Add(new SimplePassData() { Key = "passdata", Value = menu });
        data.Add(new SimplePassData() { Key = "type", Value = 0 });

        SetDialogWindowSetting(new DialogWindowSetting()
        {
            WindowWidth = 800,
            WindowHeight = 600,
            IsShowMaxButton = false,
            IsShowMinButton = false,
            IsOpenWindowSize = false,
            TitleFontSize = 15,
            CloseDialogWindowCallBackCommand = new RelayCommand<object>(ExecuteBeforeCloseDialogWindow),
            IconStr = "pack://application:,,,/Vampirewal.Admin.Server;component/Logo.png"
        });

        ExecuteShowDialogWindow(data);
    }

    [RelayCommand]
    public void AddNewMenu(Sys_Menu parent)
    {
        ViewKey = ServerViewKeys.EditClientMenuView;

        List<SimplePassData> data = new List<SimplePassData>();

        Sys_Menu menu = new Sys_Menu()
        {
            MenuType = 1,
            ListId = Guid.NewGuid().ToString(),
            ParentId = parent.ListId
        };

        data.Add(new SimplePassData() { Key = "passdata", Value = menu });
        data.Add(new SimplePassData() { Key = "type", Value = 1 });
        data.Add(new SimplePassData() { Key = "parent", Value = parent });

        SetDialogWindowSetting(new DialogWindowSetting()
        {
            WindowWidth = 800,
            WindowHeight = 600,
            IsShowMaxButton = false,
            IsShowMinButton = false,
            IsOpenWindowSize = false,
            TitleFontSize = 15,
            CloseDialogWindowCallBackCommand = new RelayCommand<object>(ExecuteBeforeCloseDialogWindow),
            IconStr = "pack://application:,,,/Vampirewal.Admin.Server;component/Logo.png"
        });

        ExecuteShowDialogWindow(data);
    }

    [RelayCommand]
    public void AddNewBtn(Sys_Menu parent)
    {
        ViewKey = ServerViewKeys.EditClientMenuView;

        List<SimplePassData> data = new List<SimplePassData>();

        Sys_Menu menu = new Sys_Menu()
        {
            MenuType = 2,
            ListId = Guid.NewGuid().ToString(),
            ParentId = parent.ListId
        };

        data.Add(new SimplePassData() { Key = "passdata", Value = menu });
        data.Add(new SimplePassData() { Key = "type", Value = 2 });
        data.Add(new SimplePassData() { Key = "parent", Value = parent });

        SetDialogWindowSetting(new DialogWindowSetting()
        {
            WindowWidth = 800,
            WindowHeight = 600,
            IsShowMaxButton = false,
            IsShowMinButton = false,
            IsOpenWindowSize = false,
            TitleFontSize = 15,
            CloseDialogWindowCallBackCommand = new RelayCommand<object>(ExecuteBeforeCloseDialogWindow),
            IconStr = "pack://application:,,,/Vampirewal.Admin.Server;component/Logo.png"
        });

        ExecuteShowDialogWindow(data);
    }

    [RelayCommand]
    public void LookMenu(Sys_Menu menu)
    {
        BottomContext = WindowsManager.GetInstance().GetView(ServerViewKeys.EditClientMenuView, Param: menu);
    }

    [RelayCommand]
    public void DeleteMenu(GeneralTreeContainer<Sys_Menu> menu)
    {
        if (menu.SubItems != null && menu.SubItems.Count > 0)
        {
            var aaa = WindowsManager.GetInstance().Windows;
            //Dialog.ShowPopupWindow($"{menu.TreeNode.MenuName} 名下存在子项，请先删除子项！", WindowsManager.GetInstance().MainWindow, MessageType.Error);
            Dialog.ShowPopupWindow(new PopupWindowSetting()
            {
                Message= $"{menu.TreeNode.MenuName} 名下存在子项，请先删除子项！",
                OwnerWindow= WindowsManager.GetInstance().MainWindow,
                Type= MessageType.Error
            });
        }
        else
        {
            try
            {
                RepBill.BeginTran();

                RepBill.Delete(menu.TreeNode.BillId);

                RepBill.CommitTran();

                MenuList.LoadFullNodes(RepBill.ToList());

                EventBusFactory.Publish("RemoveMenu", menu.TreeNode);
            }
            catch (Exception)
            {
                RepBill.RollbackTran();
            }
        }
    }

    #endregion
}

/// <summary>
/// 菜单编辑页VM
/// </summary>
[VampirewalIoCRegister(ServerViewModelKeys.EditClientMenuViewModel)]
public partial class EditClientMenuViewModel : BillVM<Sys_Menu>
{
    private SqlSugarRepository<Sys_Menu> repMenu { get; set; }

    private IVampirewalCoreDialogMessage Dialog { get; set; }

    public EditClientMenuViewModel(IVampirewalCoreDialogMessage dialog, SqlSugarRepository<Sys_Menu> _repMenu) : base(_repMenu)
    {
        repMenu = _repMenu;
        Dialog = dialog;

        RadioButtonActionsCommand = new IVampirewalCoreEventCommand[]
        {
            new VampirewalCoreEventCommand("Checked","Tag", new RelayCommand<object>((o) =>
            {
                int type=Convert.ToInt32( o);

                Entity.MenuType=type;
            }) ),
            
        };
    }

    public override void InitData()
    {
        IsCanShowPermission = false;
        IsCanShowViewPath = false;
    }

    [ObservableProperty]
    public bool isCanShowViewPath;

    [ObservableProperty]
    public bool isCanShowPermission;

    /// <summary>
    /// 父级
    /// </summary>
    [ObservableProperty]
    public Sys_Menu parent;

    public override void PassData(object obj)
    {
        var model = obj as Sys_Menu;

        if (model == null)
        {
            Title = "新增顶级模块";

            var data = obj as List<SimplePassData>;

            foreach (var item in data)
            {
                if (item.Key == "type")
                {
                    int va = Convert.ToInt32(item.Value);

                    switch (va)
                    {
                        case 0:
                            {
                                Title = "新增顶级模块";
                            }
                            break;

                        case 1:
                            {
                                Title = "新增菜单";
                                IsCanShowViewPath = true;
                            }
                            break;

                        case 2:
                            {
                                Title = "新增按钮";
                                IsCanShowPermission = true;
                            }
                            break;

                        default:
                            CloseView();
                            break;
                    }
                }

                if (item.Key == "passdata")
                {
                    SetEntity((Sys_Menu)item.Value);
                }

                if (item.Key == "parent")
                {
                    Parent = (Sys_Menu)item.Value;
                }
            }
        }
        else
        {
            if (model.MenuType == 1)
            {
                IsCanShowViewPath = true;
            }

            if (model.MenuType == 2)
            {
                IsCanShowPermission = true;
            }

            SetEntity(model);
        }
    }

    public IVampirewalCoreEventCommand[] RadioButtonActionsCommand { get; set; }

    protected override void CloseView()
    {
        WindowsManager.GetInstance().CloseDialogWindow(ViewId);
    }

    /// <summary>
    /// 保存命令
    /// </summary>
    [RelayCommand]
    public void Save()
    {
        try
        {
            repMenu.CurrentBeginTran();

            if (string.IsNullOrEmpty(Entity.BillId))
            {
                repMenu.Insert(Entity);
            }
            else
            {
                repMenu.Update(Entity);
            }

            repMenu.CurrentCommitTran();
            if (ViewId == Guid.Empty)
                //Dialog.ShowPopupWindow($"保存成功！", WindowsManager.GetInstance().MainWindow, MessageType.Successful);
                Dialog.ShowPopupWindow(new PopupWindowSetting()
                {
                    Message="保存成功!",
                    OwnerWindow = WindowsManager.GetInstance().MainWindow,
                    Type= MessageType.Successful
                });
            else
                //Dialog.ShowPopupWindow($"保存成功！", WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Successful);
                Dialog.ShowPopupWindow(new PopupWindowSetting()
                {
                    Message = "保存成功!",
                    OwnerWindow = WindowsManager.GetInstance().GetDialogWindow(ViewId),
                    Type = MessageType.Successful
                });
        }
        catch (Exception ex)
        {
            repMenu.CurrentRollbackTran();
            if (ViewId == Guid.Empty)
                //Dialog.ShowPopupWindow($"保存失败！:{ex.Message}", WindowsManager.GetInstance().MainWindow, MessageType.Error);
                Dialog.ShowPopupWindow(new PopupWindowSetting()
                {
                    Message = $"保存失败！:{ex.Message}",
                    OwnerWindow = WindowsManager.GetInstance().MainWindow,
                    Type = MessageType.Error
                });
            else
                //Dialog.ShowPopupWindow($"保存失败！:{ex.Message}", WindowsManager.GetInstance().GetDialogWindow(ViewId), MessageType.Error);
                Dialog.ShowPopupWindow(new PopupWindowSetting()
                {
                    Message = $"保存失败！:{ex.Message}",
                    OwnerWindow = WindowsManager.GetInstance().GetDialogWindow(ViewId),
                    Type = MessageType.Error
                });
        }
    }
}